import {defineStore} from 'pinia';
import {Login, Collect} from "@/api/user.js"
import {QueryAddress} from "@/api/address.js"

const useUserInfo = defineStore('userInfo', {
    state: () => {
        return {
            userInfo: {},
            addressList: [],
            activeAddressIndex: 0,
        }
    },
    persist: { // 自定义持久化方式
        storage: window.localStorage,
        beforeHydrate: context => {
            console.log('Before', context)
        },
        afterHydrate(context) {
            console.log('After', context)
        }
    },
    getters: {
        getToken() {
            return this.userInfo.token
        },
        getAddress() {
            return this.addressList
        },
        getDefaultAddress() {
            if(this.addressList.length) {
                if(this.activeAddressIndex) {
                    return this.addressList[this.activeAddressIndex]
                }
                return this.addressList.find(item => item.isDefault) || this.addressList[this.activeAddressIndex]
            }
            return {}
        },
    },
    actions: {
        // 登录操作
        async login(params) {
            const res = await Login(params)
            this.userInfo = res.data
            await this.getUserAddress()
        },
        // 收藏接口
        async collect(params) {
            const res = await Collect(params)
            this.userInfo.collectList = res.data
        },
        // 退出登录操作
        logout() {
            this.userInfo = {}
        },
        // 获取用户地址信息
        async getUserAddress() {
            const res = await QueryAddress()
            if (res.data && res.data.length) {
                res.data.forEach(item => {
                    item["address"] = item.province + item.city + item.county + item.addressDetail
                })
                res.data.sort((a, b) => b.isDefault - a.isDefault)
                this.addressList = res.data
            }
        },
        // 改变地址索引
        updateAddressIndex(index) {
            this.activeAddressIndex = index
        }
    }
});
export default useUserInfo
